package com.fingard.dsp.bank.directbank.citic02;

import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.bankInterface.IDeContract;
import com.fingard.dsp.bank.reqrespobj.contract.ContractState;
import com.fingard.dsp.bank.reqrespobj.contract.RetAtsContract;
import com.fingard.dsp.bank.reqrespobj.decontract.ReqDeContract;
import com.fingard.dsp.bank.reqrespobj.decontract.RetAtsDeContract;
import com.fingard.dsp.bank.reqrespobj.decontract.detail.RetAtsDeContractDetail;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

public class CITIC02DeContract extends CITIC02Base implements IDeContract {
    @Override
    public RetAtsDeContract deContract(ReqDeContract p_req) throws Exception {
        RetAtsDeContract retAts = new RetAtsDeContract(p_req.reqHeader);
        RetAtsDeContractDetail tmpRetDetail = new RetAtsDeContractDetail();
        tmpRetDetail.reqSeqID = p_req.contractDetail.askNumber;
        try{
            ActSetItem actItem = getBankConfig().getActSetItem(p_req.contractDetail.recAct, "");
            if(actItem ==null) {
                tmpRetDetail.respCode = "-1";
                tmpRetDetail.respInfo = "未找到账号[" + p_req.contractDetail.recAct + "]商户配置信息!1";
                retAts.writeRetDetail(tmpRetDetail);
                return retAts;
            }
            XmlTextWriter xmlWriter = new XmlTextWriter();
            xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\""+getCharset()+"\"?>");
            xmlWriter.writeStartElement("ROOT");

            if ("01".equals(p_req.contractDetail.step)) {
                xmlWriter.writeElementString("trancode", "DXJY001");
                xmlWriter.writeElementString("sndseqno", p_req.contractDetail.askNumber);
                xmlWriter.writeElementString("mccprtcno", actItem.appId);
                xmlWriter.writeElementString("mrchname", actItem.userCode);
                xmlWriter.writeElementString("mrchtype", "0401");// 0401	金融服务类-保险费
                xmlWriter.writeElementString("payname", p_req.contractDetail.payName);
                xmlWriter.writeElementString("payacc", p_req.contractDetail.payAct);
                xmlWriter.writeElementString("phone", p_req.contractDetail.cellPhone);
                xmlWriter.writeElementString("idtype", convertCertTypeToBank(p_req.contractDetail.certType));
                xmlWriter.writeElementString("idno", p_req.contractDetail.certNum);
                xmlWriter.writeElementString("protocolno", p_req.contractDetail.authCode);
                xmlWriter.writeEndDocument();
            } else if ("02".equals(p_req.contractDetail.step)) {
                xmlWriter.writeElementString("trancode", "DXYZ001");
                xmlWriter.writeElementString("sndseqno", getQryTransID());
                xmlWriter.writeElementString("osndseqno", p_req.contractDetail.askNumber);
                xmlWriter.writeElementString("mccprtcno", actItem.appId);
                xmlWriter.writeElementString("code", p_req.contractDetail.smsCode);
                xmlWriter.writeElementString("flag", "01");
                xmlWriter.writeEndDocument();
            } else {
                tmpRetDetail.respCode = "-1";
                tmpRetDetail.respInfo = "未能识别的step：" + p_req.contractDetail.step;
                retAts.writeRetDetail(tmpRetDetail);
                return retAts;
            }
            StringBuilder sbContent=new StringBuilder();
            //报文长度（8）+地区码（4）+业务种类（6）+委托单位（15）+业务单位（15）+渠道号（8）+外部交易码（15）
            String area=getBankConfig().getValueAsString("area");
            String businessTypes=getBankConfig().getValueAsString("businessTypes");
            String entrustmentUnit=getBankConfig().getValueAsString("entrustmentUnit");
            String businessUnit=getBankConfig().getValueAsString("businessUnit");
            String channelNumber=getBankConfig().getValueAsString("channelNumber");
            sbContent.append(String.format("%-4s", area));//地区码
            sbContent.append(String.format("%-6s", businessTypes));//业务种类
            sbContent.append(String.format("%-15s", entrustmentUnit));//委托单位
            sbContent.append(String.format("%-15s", businessUnit));//业务单位
            sbContent.append(String.format("%-8s", channelNumber));//渠道号
            if ("01".equals(p_req.contractDetail.step)) {
                sbContent.append(String.format("%-15s", "DXJY001"));//外部交易码
            } else {
                sbContent.append(String.format("%-15s", "DXYZ001"));//外部交易码
            }
            String tmpStrPlain = xmlWriter.toXmlString();
            String result=sbContent.toString();
            String sendMessage=result+tmpStrPlain;
            String[] tmpRetStr = sendToBank(sendMessage);
            if(tmpRetStr[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpRetStr[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    tmpRetDetail.respCode = "0";
                    tmpRetDetail.respInfo = tmpBkReader.getFirstText("/ROOT/respinfo");
                    String transStatus = tmpBkReader.getFirstText("/ROOT/stat");
                    if("01".equals(p_req.contractDetail.step)) {
                        tmpRetDetail.respCode = "0";
                        if("00".equals(transStatus)){
                            tmpRetDetail.deSignState = ContractState.SUCCESS;
                        }else {
                            tmpRetDetail.deSignState = ContractState.FAIL;
                        }
                        tmpRetDetail.step = "01";
                        tmpRetDetail.unifiedCode = getBankConfig().getMapValueByKey("contractMapping", "03"+transStatus);
                    } else {
                        if ("00".equals(transStatus) || "07".equals(transStatus)) {
                            tmpRetDetail.deSignState=ContractState.SUCCESS;
                        } else {
                            tmpRetDetail.deSignState = ContractState.FAIL;
                        }
                        tmpRetDetail.unifiedCode = getBankConfig().getMapValueByKey("contractMapping", "02"+transStatus);
                    }
                } else {
                    tmpRetDetail.respCode = "-1";
                    tmpRetDetail.respInfo = tmpSbMsg.toString();
                }
            } else {
                tmpRetDetail.respCode = "-1";
                tmpRetDetail.respInfo = tmpRetStr[1];
            }
        }catch (Exception ex) {
            ex.printStackTrace();
            tmpRetDetail.respCode = "-1";
            tmpRetDetail.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

            retAts.writeRetDetail(tmpRetDetail);
            return retAts;
    }

    @Override
    public RetAtsDeContract qryDeContract(ReqDeContract p_reqQry) throws Exception {
        return null;
    }
}
